﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using MySql.Data.MySqlClient;

namespace CarCricketMatchApp
{
    public partial class MainForm : Form
    {
        private Team team1;
        private Team team2;
        private bool isMathing = false;

        private const int MAXPASSENGER = 15;
        public MainForm()
        {
            InitializeComponent();
        }
#region delegetedefine

        delegate void LabelControlSetText(string obj);
        delegate void DataGridViewRefresh(DataTable dt);


        void setLabelFacing(string playerName)
        {
            string showLable = "Facing : " + playerName;
            if (labelFacing.InvokeRequired)
            {
                LabelControlSetText d = new LabelControlSetText(setLabelFacingMethod);
                labelFacing.Invoke(d, showLable); 

            }
            else
            {
                this.labelFacing.Text = showLable;
            }
        }

        void setLabelFacingMethod(string strPar)
        {
            this.labelFacing.Text = strPar;
        }

        void setLabelRunner(string playerName)
        {
            string showlabel = "Runner : " + playerName;
            if (labelRunner.InvokeRequired)
            {
                LabelControlSetText d = new LabelControlSetText(setLabelRunnerMethod);
                this.labelRunner.Invoke(d, showlabel);
            }else
            {
                labelRunner.Text = showlabel;
            }
        }

        void setLabelRunnerMethod(string strpar)
        {
            this.labelRunner.Text = strpar;
        }

        void  setLabelNextBall(string ballName)
        {
            string showLabel = "InComingCar: " + ballName;
            if (labelIncoming.InvokeRequired)
            {
                LabelControlSetText d = new LabelControlSetText(setLabelNextBallMethod);
                labelIncoming.Invoke(d, showLabel); 
            }else
            {
                labelIncoming.Text = showLabel;
            }
        }

        void setLabelNextBallMethod(string strPar)
        {
            this.labelIncoming.Text = strPar;
        }

        void setLabelTeam1Score(string scores)
        {
            string showLabel = "Team1 Scores : " + scores;
            if (this.labelTeam1Scores.InvokeRequired)
            {

                LabelControlSetText d = new LabelControlSetText(setLabelTeam1ScoreMethod);
                labelTeam1Scores.Invoke(d, showLabel);
            }else
            {

                labelTeam1Scores.Text = showLabel;
            }
        }

        void setLabelTeam1ScoreMethod(string strPar)
        {
            this.labelTeam1Scores.Text = strPar;
        }

        void setLabelTeam2Score(string scores)
        {
            string showLabel = "Team2 Scores : " + scores;
            if (this.labelTeam2Scores.InvokeRequired)
            {

                LabelControlSetText d = new LabelControlSetText(setLabelTeam2ScoreMethod);
                labelTeam2Scores.Invoke(d, showLabel);
            }
            else
            {

                labelTeam2Scores.Text = showLabel;
            }
        }

        void setLabelTeam2ScoreMethod(string strPar)
        {
            this.labelTeam2Scores.Text = strPar;
        }

        void refreshDataridView1(DataTable dt)
        {
            if (this.dataGridViewTeam1.InvokeRequired)
            {
                DataGridViewRefresh d = new DataGridViewRefresh(refreshDataridView1Method);
                this.dataGridViewTeam1.Invoke(d, dt);
            }
            else
            {

                this.dataGridViewTeam1.DataSource = dt;
                this.dataGridViewTeam1.Refresh();

                try
                {
                    this.dataGridViewTeam1.Columns[0].Width = COLUMNWIDTH;
                    this.dataGridViewTeam1.Columns[3].Width = COLUMNWIDTH;
                    this.dataGridViewTeam1.Columns[4].Width = COLUMNWIDTH;
                    this.dataGridViewTeam1.Columns[5].Width = COLUMNWIDTH;
                }
                catch (System.Exception ex)
                {
                    Debug.Print(ex.ToString());
                }
                
            }
        }

        void refreshDataridView1Method(DataTable dt)
        {
            this.dataGridViewTeam1.DataSource = dt;
            this.dataGridViewTeam1.Refresh();
            try
            {
                this.dataGridViewTeam1.Columns[0].Width = COLUMNWIDTH;
                this.dataGridViewTeam1.Columns[3].Width = COLUMNWIDTH;
                this.dataGridViewTeam1.Columns[4].Width = COLUMNWIDTH;
                this.dataGridViewTeam1.Columns[5].Width = COLUMNWIDTH;
            }
            catch (System.Exception ex)
            {
                Debug.Print(ex.ToString());
            }
                
        }

        void refreshDatagidView2(DataTable dt)
        {
            if (this.dataGridViewTeam2.InvokeRequired)
            {
                DataGridViewRefresh d = new DataGridViewRefresh(refreshDataridView2Method);
                this.dataGridViewTeam2.Invoke(d, dt);
            }
            else
            {

                this.dataGridViewTeam2.DataSource = dt;
                this.dataGridViewTeam2.Refresh();
                //set the column width
                try
                {
                    //1 column
                    this.dataGridViewTeam2.Columns[0].Width = COLUMNWIDTH;

                    //
                    this.dataGridViewTeam2.Columns[3].Width = COLUMNWIDTH;
                    this.dataGridViewTeam2.Columns[4].Width = COLUMNWIDTH;
                    this.dataGridViewTeam2.Columns[5].Width = COLUMNWIDTH;
                }
                catch (System.Exception ex)
                {
                    Debug.Print(ex.ToString());
                }
               
            }
        }

        void refreshDataridView2Method(DataTable dt)
        {
            this.dataGridViewTeam2.DataSource = dt;
            this.dataGridViewTeam2.Refresh();
            try
            {
                this.dataGridViewTeam2.Columns[0].Width = COLUMNWIDTH;
                this.dataGridViewTeam2.Columns[3].Width = COLUMNWIDTH;
                this.dataGridViewTeam2.Columns[4].Width = COLUMNWIDTH;
                this.dataGridViewTeam2.Columns[5].Width = COLUMNWIDTH;

            }
            catch (System.Exception ex)
            {
                Debug.Print(ex.ToString());
            }
        }

        private const  int COLUMNWIDTH = 50;
#endregion
#region button click handler

        private void buttonExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        
#endregion

        #region init the data

        private void InitPasseng1()
        {
            foreach (ListViewItem item in this.listViewPassenge1.Items)
            {
                this.listViewPassenge1.Items.Remove(item);
            }
            List<Passenger> list = new List<Passenger>();
            for (int i = 0; i < 15; i++)
            {
                Passenger passeng = new Passenger("test" + i.ToString());
                list.Add(passeng);
            }
            
            ListViewItem[] p = new ListViewItem[15];
            for(int j=0; j < 15;j ++)
            {
                p[j] = new ListViewItem(new string[] { list[j].PlayerName});
            }
            this.listViewPassenge1.Items.AddRange(p);
        }
       
       

        #endregion

        #region passenger1 

        private void buttonPasseng1AddPlayer_Click(object sender, EventArgs e)
        {
            try
            {
                 // first confirm if select one of passenger
                if (this.listViewPassenge1.SelectedItems.Count ==0)
                {
                    MessageBox.Show("You must select at least one passenger!");
                    return;
                }
                ListViewItem item = this.listViewPassenge1.SelectedItems[0];
                string passengerName = item.Text;

                string teamname = this.txtboxName1.Text;
                if (teamname.Equals(""))
                {
                    MessageBox.Show("You should input you name!");
                    return;
                }
                // craete team1
                if (team1 == null)
                {
                    team1 = new Team(teamname);
                }
                else
                {
                    team1.Name = teamname;
                }

              
                //now we new a player
                Player player = null;

                //set the player playerstyles
                SelectPlaystylesForm selectForm = new SelectPlaystylesForm();
                if(selectForm.ShowDialog() ==  DialogResult.OK)
                {
                    player = new Player(team1, selectForm.SelectStyle, passengerName);
                }
                else
                {
                    MessageBox.Show("You should select one of PlayerStyles");
                    return;
                }
                // add the player to the team1
                team1.addPlayerToTheTeam(player);

                //and refresh 
                refreshTeam1DataGridView();

                //when add success, remove from list view
                this.listViewPassenge1.Items.Remove(item);

            }
            catch (System.Exception ex)
            {
            	MessageBox.Show(ex.Message);
            }

        }

        private void refreshTeam1DataGridView()
        {
            // generator datatable
            DataTable dt = new DataTable();
            //contains 6 columns

            DataColumn dc1 = new DataColumn("Order");
            dc1.Caption = "Order";

            DataColumn dc2 = new DataColumn("PlayerName");
            dc2.Caption = "PlayerName";

            DataColumn dc3 = new DataColumn("Style");
            dc2.Caption = "Style";

            DataColumn dc4 = new DataColumn("LastScore");
            dc2.Caption = "LastScore";

            DataColumn dc5 = new DataColumn("Inningscount");
            dc2.Caption = "Inningscount";

            DataColumn dc6 = new DataColumn("OutCount");
            dc2.Caption = "OutCount";

            
            dt.Columns.Add(dc1);
            dt.Columns.Add(dc2);
            dt.Columns.Add(dc3);
            dt.Columns.Add(dc4);
            dt.Columns.Add(dc5);
            dt.Columns.Add(dc6);
            
            //add row
            foreach (Player item in team1.Players)
            {
                DataRow dr1 = dt.NewRow();
                dr1["Order"] = item.OrderIndex;
                dr1["PlayerName"] = item.PlayerName;
                dr1["Style"] = item.Style;
                dr1["LastScore"] = item.LastScore;
                dr1["Inningscount"] = item.Inningscount;
                dr1["OutCount"] = item.OutCount;
                dt.Rows.Add(dr1);
            }

            refreshDataridView1(dt);
        }
        #endregion


        #region passenger2
        private void InitPasseng2()
        {
            foreach (ListViewItem item in this.listViewPassenger2.Items)
            {
                this.listViewPassenger2.Items.Remove(item);
            }
            List<Passenger> list = new List<Passenger>();
            for (int i = 0; i < 15; i++)
            {
                Passenger passeng = new Passenger("name_" + i.ToString() );
                list.Add(passeng);
            }

            ListViewItem[] p = new ListViewItem[15];
            for (int j = 0; j < 15; j++)
            {
                p[j] = new ListViewItem(new string[] { list[j].PlayerName });
            }
            this.listViewPassenger2.Items.AddRange(p);
        }

        private void buttonPasseng1AddPlayer2_Click(object sender, EventArgs e)
        {
            try
            {
                // first confirm if select one of passenger
                if (this.listViewPassenger2.SelectedItems.Count == 0)
                {
                    MessageBox.Show("You must select at least one passenger!");
                    return;
                }
                ListViewItem item = this.listViewPassenger2.SelectedItems[0];
                string passengerName = item.Text;

                string teamname = this.txtBoxName2.Text;
                if (teamname.Equals(""))
                {
                    MessageBox.Show("You should input you name!");
                    return;
                }
                // craete team2
                if (team2 == null)
                {
                    team2 = new Team(teamname);
                }
                else
                {
                    team2.Name = teamname;
                }


                //now we new a player
                Player player = null;

                //set the player playerstyles
                SelectPlaystylesForm selectForm = new SelectPlaystylesForm();
                if (selectForm.ShowDialog() == DialogResult.OK)
                {
                    player = new Player(team2, selectForm.SelectStyle, passengerName);
                }
                else
                {
                    MessageBox.Show("You should select one of PlayerStyles");
                    return;
                }
                // add the player to the team1
                team2.addPlayerToTheTeam(player);

                //and refresh 
                refreshTeam2DataGridView();
                //when add successful,remvoe from list view

                this.listViewPassenger2.Items.Remove(item);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void refreshTeam2DataGridView()
        {
            // generator datatable
            DataTable dt = new DataTable();
            //contains 6 columns

            DataColumn dc1 = new DataColumn("Order");
            
            dc1.Caption = "Order";

            DataColumn dc2 = new DataColumn("PlayerName");
            dc2.Caption = "PlayerName";

            DataColumn dc3 = new DataColumn("Style");
            dc2.Caption = "Style";

            DataColumn dc4 = new DataColumn("LastScore");
            dc2.Caption = "LastScore";

            DataColumn dc5 = new DataColumn("Inningscount");
            dc2.Caption = "Inningscount";

            DataColumn dc6 = new DataColumn("OutCount");
            dc2.Caption = "OutCount";


            dt.Columns.Add(dc1);
            dt.Columns.Add(dc2);
            dt.Columns.Add(dc3);
            dt.Columns.Add(dc4);
            dt.Columns.Add(dc5);
            dt.Columns.Add(dc6);

            //add row
            foreach (Player item in team2.Players)
            {
                DataRow dr1 = dt.NewRow();
                dr1["Order"] = item.OrderIndex;
                dr1["PlayerName"] = item.PlayerName;
                dr1["Style"] = item.Style;
                dr1["LastScore"] = item.LastScore;
                dr1["Inningscount"] = item.Inningscount;
                dr1["OutCount"] = item.OutCount;
                
                dt.Rows.Add(dr1);
            }

            refreshDatagidView2(dt);

            //set column width
            
        }
        #endregion
        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void dataGridViewTeam1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
             DataGridView dgv = (DataGridView)sender; 
　　        string name = dgv.Columns[e.ColumnIndex].Name;
            // only change the order
          if ("Order" != name)
          {
              // cancel the editor
              e.Cancel = true;
          }
          else
          {
              string value = (string)dgv[name, e.RowIndex].Value;
              try
              {
                  int order = int.Parse(value);
              }
              catch (Exception exp)
              {
                  e.Cancel = true;
                  MessageBox.Show(exp.Message);
              }
          }
        }

        private void dataGridViewTeam1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            DataGridView dgv = (DataGridView)sender; 
　　        string name = dgv.Columns[e.ColumnIndex].Name;
            
            // only change the order
          if ("Order" == name)
          {

              string value = (string)dgv[name, e.RowIndex].Value;
              string playerName = (string)dgv["PlayerName", e.RowIndex].Value;
              // get the current player of team
              Player player = team1.getPlayerByName(playerName);
              if (player != null)
              {
                  // change the player order of team1
                  try
                  {
                      player.OrderIndex = int.Parse(value);
                  }
                  catch (Exception exp)
                  {
                      MessageBox.Show(exp.Message);
                      dgv["Order", e.RowIndex].Value = 0;
                  }


              }
              else
              {
                  MessageBox.Show("Chang order error!");
              }
             
          }
          
        }


        private void dataGridViewTeam2_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            DataGridView dgv = (DataGridView)sender;
            string name = dgv.Columns[e.ColumnIndex].Name;

            // only change the order
            if ("Order" == name)
            {

                string value = (string)dgv[name, e.RowIndex].Value;
                string playerName = (string)dgv["PlayerName", e.RowIndex].Value;
                // get the current player of team
                Player player = team2.getPlayerByName(playerName);
                if (player != null)
                {
                    // change the player order of team1
                    try
                    {
                        player.OrderIndex = int.Parse(value);
                    }
                    catch (Exception exp)
                    {
                        MessageBox.Show(exp.Message);
                        dgv["Order", e.RowIndex].Value = 0;
                    }


                }
                else
                {
                    MessageBox.Show("Chang order error!");
                }

            }
        }

        private void dataGridViewTeam2_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            DataGridView dgv = (DataGridView)sender;
            string name = dgv.Columns[e.ColumnIndex].Name;
            // only change the order
            if ("Order" != name)
            {
                // cancel the editor
                e.Cancel = true;
            }
        }
        private void MainForm_Load(object sender, EventArgs e)
        {
            //init null
            //InitPasseng1();
            //InitPasseng2();
        }

        private void buttonReset_Click(object sender, EventArgs e)
        {
            // reset the current state
            this.team1 = new Team(this.txtboxName1.Text);
            this.team2 = new Team(this.txtBoxName2.Text);

            //resset the dataGridView

            refreshTeam2DataGridView();
            refreshTeam1DataGridView();


            //reset the list view
            foreach (ListViewItem item in this.listViewPassenger2.Items)
            {
                this.listViewPassenger2.Items.Remove(item);
            }
            foreach (ListViewItem item in this.listViewPassenge1.Items)
            {
                this.listViewPassenge1.Items.Remove(item);
            }

            //reset the player account
            this.team1TotalAccount = 0;
            this.team2TotalAccount = 0;
        }

        private void buttonPlay_Click(object sender, EventArgs e)
        {
            try
            {
                isMathing = true;
                //set the init score is 0
                this.labelTeam1Scores.Text = "Team1 Scores: 0 ";
                this.labelTeam2Scores.Text = "Team2 Scores: 0 ";
                this.backgroundWorker1.RunWorkerAsync();
              
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
                isMathing = false;
            }
        }

        void match_PlayNextBallEvent(object sender, PlayNextBallEventArgs e)
        {
            //
            setLabelNextBall(e.NextBall.ToString());
            //MessageBox.Show(e.NextBall.ToString());
            //refresh grid1 and grid 2
            refreshTeam1DataGridView();
            refreshTeam2DataGridView();
        }

        private void buttonRandomTeam_Click(object sender, EventArgs e)
        {
            //random generator team1
            team1 = new Team(this.txtboxName1.Text);
            Random random = new Random();
            for (int i = 1; i <= 11;i++ )
            {
                try
                {
                    int style = random.Next(0, 2);
                    PlayerStyles styleT = PlayerStyles.Hitter;
                    switch (style)
                    {
                        case 0:
                            styleT = PlayerStyles.Hitter;
                            break;
                        case 1:
                            styleT = PlayerStyles.Balanced;
                            break;
                        case 2:
                            styleT = PlayerStyles.Defensive;
                            break;
                        default:
                            break;
                    }
                    Player player = new Player(team1, styleT, "test11_" + i.ToString());
                    team1.addPlayerToTheTeam(player);
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }

            }
            refreshTeam1DataGridView();
            //random generator team2
            team2 = new Team(this.txtBoxName2.Text);
            for (int i = 0; i < 11; i++)
            {
                try
                {
                    int style = random.Next(0, 2);
                    PlayerStyles styleT = PlayerStyles.Hitter;
                    switch (style)
                    {
                        case 0:
                            styleT = PlayerStyles.Hitter;
                            break;
                        case 1:
                            styleT = PlayerStyles.Balanced;
                            break;
                        case 2:
                            styleT = PlayerStyles.Defensive;
                            break;
                        default:
                            break;
                    }
                    Player player = new Player(team2, styleT, "test22_" + i.ToString());
                    team2.addPlayerToTheTeam(player);
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }

            }
            refreshTeam2DataGridView();
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {

                Match match = new Match(team1, team2);

                if (team1.isRestart())
                {
                    MessageBox.Show("You should reset the team");
                    return;
                }
                if (team2.isRestart())
                {
                    MessageBox.Show("You should reset the team");
                        return;
                }
                match.PlayNextBallEvent += new PlayNextBallEventHandler(match_PlayNextBallEvent);
                match.MatchCompleteEvent += new MatchCompleteEventHandler(match_MatchCompleteEvent);
                match.FacingChangeEvent += new FacingChangeEventHandler(match_FacingChangeEvent);
                match.RunnerChangeEvent += new RunnerChangeEventHandler(match_RunnerChangeEvent);
                match.MaxVechilEvent += new MaxVechileAccount(match_MaxVechilEvent);
                match.Play();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
                isMathing = false;
            }
            
        }

        void match_MaxVechilEvent(object sender, MatchCompletEventArgs e)
        {
            MessageBox.Show(e.Data);
        }

        void match_RunnerChangeEvent(object sender, MatchCompletEventArgs e)
        {
            setLabelRunner(e.Data);
        }

        void match_FacingChangeEvent(object sender, MatchCompletEventArgs e)
        {
            setLabelFacing(e.Data);
        }

       
        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {

        }

        void match_MatchCompleteEvent(object sender, MatchCompletEventArgs e)
        {
            //on complete show last message
            MessageBox.Show(e.Data);
            //set score
            setLabelTeam1Score( e.Team1Score);
            setLabelTeam2Score( e.Team2Score );
            isMathing = false;
        }
        #region 
        private void buttonPassengAdd_Click(object sender, EventArgs e)
        {
            try
            {
                if (isMathing)
                {
                    MessageBox.Show("Matching, can not upate");
                    return;
                }
                //add player to the player 1
                AddPlayerForm addForm = new AddPlayerForm();
                if (addForm.ShowDialog() == DialogResult.OK)
                {
                    
                    //add to team
                    if (team1 == null)
                    {
                        if (this.txtboxName1.Text.Equals(""))
                        {
                            MessageBox.Show("Team should not null");
                            return;
                        }
                        team1 = new Team(this.txtboxName1.Text);
                    }
                    Player newPlayr = new Player(team1, addForm.SelectStyle, addForm.PlayerName);

                    /// if team2 exist player
                    if (team2 != null)
                    {
                        if (team2.isExistPlayer(newPlayr))
                        {
                            MessageBox.Show("Player alread exist");
                            return;
                        }
                    }
                    team1.addPlayerToTheTeam(newPlayr);

                    refreshTeam1DataGridView();
                }
                else
                {
                    MessageBox.Show("Failure ");
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message); 
            }
    
        }

        private void buttonTeam1Plus_Click(object sender, EventArgs e)
        {
            try
            {
                if (isMathing)
                {
                    MessageBox.Show("Matching, can not upate");
                    return;
                }
                DataGridViewSelectedRowCollection collection = this.dataGridViewTeam1.SelectedRows;
                if (collection.Count == 0)
                {
                    MessageBox.Show("you should select players");
                    return;
                }
                foreach (DataGridViewRow item in collection)
                {
                    Debug.Print("");

                    try
                    {
                        int index = item.Index;

                        // get the player
                        Player player = (Player)team1.Players[index];
                        //add to the passenger
                        if (player != null)
                        {
                            ListViewItem newItem = new ListViewItem(new string[] { player.PlayerName });
                            this.listViewPassenge1.Items.Add(newItem);
                        }

                        team1.deletePlayerByIndex(index);
                        refreshTeam1DataGridView();

                       

                    }
                    catch (System.Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                    
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void buttonTeam2Add_Click(object sender, EventArgs e)
        {
            try
            {
                if (isMathing)
                {
                    MessageBox.Show("Matching, can not upate");
                    return;
                }
                //add player to the player 1
                AddPlayerForm addForm = new AddPlayerForm();
                if (addForm.ShowDialog() == DialogResult.OK)
                {
                   
                    //add to team
                    if (team2 == null)
                    {
                        if (this.txtBoxName2.Text.Equals(""))
                        {
                            MessageBox.Show("Team should not null");
                            return;
                        }
                        team2 = new Team(this.txtBoxName2.Text);
                    }
                    Player newPlayr = new Player(team2, addForm.SelectStyle, addForm.PlayerName);

                    /// if team2 exist player
                    if (team1 != null)
                    {
                        if (team1.isExistPlayer(newPlayr))
                        {
                            MessageBox.Show("Player alread exist");
                            return;
                        }
                    }
                    team2.addPlayerToTheTeam(newPlayr);

                    refreshTeam2DataGridView();
                }
                else
                {
                    MessageBox.Show("Failure ");
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void buttonTeam2Plus_Click(object sender, EventArgs e)
        {
            try
            {
                if (isMathing)
                {
                    MessageBox.Show("Matching, can not upate");
                    return;
                }
                DataGridViewSelectedRowCollection collection = this.dataGridViewTeam2.SelectedRows;
                if (collection.Count == 0)
                {
                    MessageBox.Show("you should select players");
                    return;
                }
                foreach (DataGridViewRow item in collection)
                {
                    Debug.Print("");

                    try
                    {
                        int index = item.Index;
                        // get the player
                        Player player = (Player)team2.Players[index];
                        //add to the passenger
                        if (player != null)
                        {
                            ListViewItem newItem = new ListViewItem(new string[] { player.PlayerName });
                            this.listViewPassenger2.Items.Add(newItem);
                        }

                        team2.deletePlayerByIndex(index);
                        refreshTeam2DataGridView();

                     
                    }
                    catch (System.Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }

                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region passenger list add and redue function
        private void buttonAddPass1_Click(object sender, EventArgs e)
        {
            string newName = this.txtnewPasseng1.Text;
            if (newName == "")
            {
                MessageBox.Show("Name is null");
                return;
            }
                // if exist
            if (!ifExistInTheListView(newName))
            {
                if (!ifMaxAccountTeam1(newName))
                {
                    Passenger passeng = new Passenger(newName);
                    this.listViewPassenge1.Items.Add(new ListViewItem(new string[] { passeng.PlayerName }));
                    team1TotalAccount += 1;
                }
                else
                    MessageBox.Show("Passenger max is 15");
            }
            else
            {
                MessageBox.Show("passenger already exists");
            }
        }

        private bool ifExistInTheListView(string name)
        {
            foreach (ListViewItem listItem in this.listViewPassenge1.Items)
            {
                if (listItem.Text == name)
                    return true;
            }
            foreach (ListViewItem listItem2 in this.listViewPassenger2.Items)
            {
                if (listItem2.Text == name)
                    return true;
            }
           return false;
        }

        private int team1TotalAccount = 0;
        private bool ifMaxAccountTeam1(string name)
        {
            
            //int count = 0;
            //foreach (ListViewItem listItem in this.listViewPassenge1.Items)
            //{
            //    count += 1;
            //}


            if (team1TotalAccount >= MAXPASSENGER)
                return true;
            else
                return false;
        }

        private int team2TotalAccount = 0;
        private bool ifMaxAccountTeam2(string name)
        {

            //int count = 0;
            //foreach (ListViewItem listItem in this.listViewPassenger2.Items)
            //{
            //    count += 1;
            //}


            if (team2TotalAccount >= MAXPASSENGER)
                return true;
            else
                return false;
        }
        private void buttonReducepass1_Click(object sender, EventArgs e)
        {
            if (this.listViewPassenge1.SelectedItems.Count == 0)
            {
                MessageBox.Show("You must selectitems");
            }
            else
            {
                foreach (ListViewItem seleItem in this.listViewPassenge1.SelectedItems)
                {
                    this.listViewPassenge1.Items.Remove(seleItem);
                    team1TotalAccount -= 1;
                }
            }
        }

        private void buttonAddPass2_Click(object sender, EventArgs e)
        {
            string newName = this.txtnewPasseng2.Text;
            if (newName == "")
            {
                MessageBox.Show("Name is null");
                return;
            }
            // if exist
            if (!ifExistInTheListView(newName))
            {
                if (!ifMaxAccountTeam2(newName))
                {
                    Passenger passeng = new Passenger(newName);
                    this.listViewPassenger2.Items.Add(new ListViewItem(new string[] { passeng.PlayerName }));
                    team2TotalAccount += 1;
                }else
                    MessageBox.Show("Passenger max is 15");
            }
            else
            {
                MessageBox.Show("passenger already exists");
            }
        }

        private void buttonReducepass2_Click(object sender, EventArgs e)
        {
            if (this.listViewPassenger2.SelectedItems.Count == 0)
            {
                MessageBox.Show("You must selectitems");
            }
            else
            {
                foreach (ListViewItem seleItem in this.listViewPassenger2.SelectedItems)
                {
                    this.listViewPassenger2.Items.Remove(seleItem);
                    team2TotalAccount -= 1;
                }
            }
        }

        #endregion



        #region mysql operator


        #endregion

        private void button1_Click(object sender, EventArgs e)
        {
            //Player temp = new Player("test1");
            //temp.PlayerName = "test1";
            //temp.Inningscount = 100;
            //temp.LastScore = 40000;
            //temp.OutCount = 33333;
            //temp.OwnTeam = new  Team("123");
           // temp.Style = PlayerStyles.Balanced;
            DBHelper help = new DBHelper();
            help.getPlayer("test11_1");

           // deleteAllPlayer();
            //updatePlayer(temp);
        }




    }
}
